package com.xishu.controller;

import com.xishu.entity.order.Order;
import com.xishu.entity.shop.Reason;
import com.xishu.entity.shop.Shop;
import com.xishu.response.ResponseData;
import com.xishu.response.VerifyUtil;
import com.xishu.service.CommonService;
import com.xishu.service.order.base.OrderService;
import com.xishu.service.ShopService;
import com.xishu.util.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@Api(description = "特殊取消操作")
@RestController
public class ReasonController implements Tools {
    private CommonService commonService = CommonService.getInstance();

    @ApiOperation(value = "创建特殊操作理由")
    @PostMapping(value = ("/user/reason"), produces = ("application/json;charset=UTF-8"))
    public ResponseData create(@RequestBody Reason reason) throws Exception {
        Long shopId = reason.getShopId();
        VerifyUtil.verify(() -> shopId != null);
        VerifyUtil.verify(() -> reason.getType() != null);
        VerifyUtil.verify(() -> isNotEmpty(reason.getCancelTypeList()));

        Shop shop = ShopService.getInstance().findShopById(shopId);
        reason.setShopName(shop.getName());

        //如果订单存在，写到订单里面
        if (reason.getOrderId() != null) {
            Long orderId = reason.getOrderId();
            Order order = OrderService.getInstance().findOrder(shopId, orderId);
            order.setReturnReasonList(reason.getCancelTypeList());
            commonService.save(order);
        }

        for (Long cancelType : reason.getCancelTypeList()) {
            Reason newReason = new Reason();
            BeanUtils.copyProperties(reason, newReason);
            newReason.setCancelType(cancelType);
            commonService.createObject(newReason);
        }

        return commonService.createResponse(reason);
    }


    //    @ApiOperation(value = "查询特殊操作理由")
//    @PutMapping(value = ("/user/reason"), produces = ("application/json;charset=UTF-8"))
    public ResponseData list(@RequestBody Reason reason) throws Exception {
        return commonService.searchResponse(reason);
    }
}
